package com.zline.foodraise.ui.activity;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.provider.SyncStateContract;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.TextHttpResponseHandler;
import com.zline.foodraise.R;
import com.zline.foodraise.constant.Constant;
import com.zline.foodraise.entity.AppPref_;
import com.zline.foodraise.entity.CustomerUserBean;
import com.zline.foodraise.http.HttpErro;
import com.zline.foodraise.http.HttpOperator;
import com.zline.foodraise.http.HttpUtil;
import com.zline.foodraise.util.LUtil;
import com.zline.foodraise.util.NetworkUtil;
import com.zline.foodraise.util.StringUtils;
import com.zline.foodraise.util.TUtil;

import org.androidannotations.annotations.AfterInject;
import org.androidannotations.annotations.AfterTextChange;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.EBean;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.DrawableRes;
import org.androidannotations.annotations.res.StringRes;
import org.androidannotations.annotations.sharedpreferences.Pref;
import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashSet;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

/**
 * Created by heshantao on 15/7/20.
 * 用户登录界面
 */
@EActivity(R.layout.activity_login)
public class LoginActivity extends ZlineActivity {
    private static final String LOG_TAG = LoginActivity.class.getSimpleName();
    @ViewById(R.id.app_common_header_title_tv)
    TextView title_tv;
    @StringRes(R.string.login)
    String titleRes;
    @ViewById(R.id.login_phone_set_et)
    EditText phone_et;
    @ViewById(R.id.auth_code_et)
    EditText auth_code_et;
    @ViewById(R.id.accept_auth_code_tv)
    TextView accept_auth_code_tv;
    @ViewById(R.id.login_btn)
    Button login_btn;
    @ViewById(R.id.voic_auth_code_tv)
    TextView voice_auth_code_et;
    @ViewById(R.id.voic_auth_code_rl)
    RelativeLayout voic_auth_code_rl;
    @ViewById(R.id.click_voic_auth_code_rl)
    RelativeLayout click_voice_auth_code_rl;
    Timer t;
    TimerTask tt;
    long length = 60 * 1000;//倒计时长度
    long time;
    @StringRes(R.string.accept_auth_code)
    String beferText;//倒计时前显示
    String afterText;//倒计时后显示
    boolean isTime = false;//是否在倒计时
    @Bean
    HttpUtil httpUtil;
    @Bean
    HttpOperator httpOperator;
    int resultCode = 0;
    @Bean
    HttpErro httpErro;
    String phoneNumber;
    String authCode;
    @Pref
    AppPref_ appPref;
    @Bean
    NetworkUtil networkUtil;


    @AfterViews
    void doSomeAfterView() {
        initView();
    }

    void initView() {
        title_tv.setText(titleRes);
    }

    //当电话号码为11位时候可以获取验证码可以点击
    @AfterTextChange(R.id.login_phone_set_et)
    void acceptAuthCodeBgChange() {
        if (phone_et.getText().toString().length() == 11 && !isTime) {
            changeAcceptTvStatus(true);
        } else {
            changeAcceptTvStatus(false);
        }
    }

    //验证码有无内容判断登录按钮是否可用
    @AfterTextChange(R.id.auth_code_et)
    void LoginBtnBgChange() {
        authCode = auth_code_et.getText().toString().trim();
        phoneNumber = phone_et.getText().toString().trim();
        if (!StringUtils.isBlank(authCode) && !StringUtils.isBlank(phoneNumber)) {
            changeLoginBtnStatus(true);
        } else {
            changeLoginBtnStatus(false);
        }
    }


    AsyncHttpResponseHandler authoCodeHandler = new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            LUtil.i(LOG_TAG, "____successs__________" + statusCode + response.toString());
            if (statusCode == 200) {
                try {
                    resultCode = response.getInt(Constant.RESULT_CODE);
                    if (resultCode == 200) {//调用成功

                    } else {
                        httpErro.showLoginErroResult(resultCode);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
        }
    };


    AsyncHttpResponseHandler voiceAuthoCodeHandler = new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            LUtil.i(LOG_TAG, "__voice__successs__________" + statusCode + response.toString());
            if (statusCode == 200) {
                try {
                    resultCode = response.getInt(Constant.RESULT_CODE);
                    if (resultCode == 200) {//调用成功
                        showVoicAuthCodeHint();
                    } else {
                        httpErro.showLoginErroResult(resultCode);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
        }
    };


    AsyncHttpResponseHandler loginHandler = new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            LUtil.i(LOG_TAG, "__login__successs__________" + statusCode + response.toString());
            if (statusCode == 200) {
                try {
                    resultCode = response.getInt(Constant.RESULT_CODE);
                    if (resultCode == 200) {//调用成功
                        JSONObject jsonObject = response.getJSONObject(Constant.USER_BEAN);
                        String token = response.getString(Constant.ACCESS_TOKEN);
                        appPref.edit().token().put(token).apply();
                        save2PreferenceAndSetJpush(jsonObject);
                        setResult();
                    } else {
                        httpErro.showLoginErroResult(resultCode);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    dissLoadingDialog();
                }
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
            dissLoadingDialog();
        }
    };

    //将一些信息进行本地缓存并且设置推送信息
    void save2PreferenceAndSetJpush(JSONObject json) throws Exception {
        String userInfo = json.toString();
        Gson gson = new Gson();
        CustomerUserBean userBean = gson.fromJson(userInfo, CustomerUserBean.class);
        if (userBean != null) {
            long userId = userBean.getUserId();
            appPref.edit().userId().put(userId).apply();
            String userIcon = userBean.getAvatarPicUrl();
            appPref.edit().userIcon().put(userIcon).apply();
            int identificateType = userBean.getIdentificateType();
            appPref.edit().identificateType().put(identificateType).apply();
            String userIdStr = userId + "";
            if (StringUtils.isEmpty(userIdStr)) {
                TUtil.showShort(this, R.string.error_alias_empty);
                return;
            }
            if (!StringUtils.isValidTagAndAlias(userIdStr)) {
                TUtil.showShort(this, R.string.error_tag_gs_empty);
                return;
            }
            JPushInterface.setAliasAndTags(this, userId + "", null, mAliasCallback);
        }
    }

    //推送设置别名回调
    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {
        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    LUtil.i(LOG_TAG, logs);
                    break;
                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    LUtil.i(LOG_TAG, logs);
                    setAlias(alias);
                    break;
                default:
                    logs = "Failed with errorCode = " + code;
                    LUtil.i(LOG_TAG, logs);
            }
        }
    };

    //设置别名
    @Background(delay = 60000)
    void setAlias(String alias) {
        JPushInterface.setAliasAndTags(this, alias, null, mAliasCallback);
    }

    //发送验证码
    void sendAuthCode() {
        phoneNumber = phone_et.getText().toString().trim();
        if (networkUtil.isNetworkAvailable()) {
            httpOperator.sendAuthCode(httpUtil, phoneNumber, authoCodeHandler);
            starTimer();
        } else {
            TUtil.showShort(LoginActivity.this, R.string.no_network);
        }
    }

    void setResult() {
        Intent intent = new Intent();
        this.setResult(Constant.LOGIN_RESULT_CODE, intent);
        this.finish();
    }

    //语言验证码
    void sendVoiceAuthCode() {
        phoneNumber = phone_et.getText().toString().trim();
        if (StringUtils.isBlank(phoneNumber)) {
            TUtil.showShort(this, R.string.login_phone_set_hint);
            return;
        }
        httpOperator.sendVoiceAuthCode(httpUtil, phoneNumber, voiceAuthoCodeHandler);
    }

    //登录
    void login() {
        phoneNumber = phone_et.getText().toString().trim();
        authCode = auth_code_et.getText().toString().trim();
        if (networkUtil.isNetworkAvailable()) {
            showLoadingDialog();
            httpOperator.login(httpUtil, phoneNumber, authCode, loginHandler);
        } else {
            TUtil.showShort(LoginActivity.this, R.string.no_network);
        }
    }

    //获取语音验证码成功
    void showVoicAuthCodeHint() {
        voic_auth_code_rl.setVisibility(View.GONE);
        click_voice_auth_code_rl.setVisibility(View.VISIBLE);

    }


    @Click({R.id.app_common_header_left_icon_iv, R.id.accept_auth_code_tv,
            R.id.login_btn, R.id.voic_auth_code_tv
    })
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.app_common_header_left_icon_iv:
                goback();
                break;
            case R.id.accept_auth_code_tv:
                sendAuthCode();
                break;
            case R.id.login_btn:
                login();
                break;
            case R.id.voic_auth_code_tv:
                sendVoiceAuthCode();
                break;
            default:
                break;
        }

    }

    //启动发送验证码定时器
    void starTimer() {
        initTimer();
        afterText = getResources().getString(R.string.send_auth_code_again, time / 1000);
        accept_auth_code_tv.setText(afterText);
        t.schedule(tt, 0, 1000);
    }

    //初始化定时器
    void initTimer() {
        time = length;
        isTime = true;
        t = new Timer();
        tt = new TimerTask() {
            @Override
            public void run() {
                setAcceptTv();
            }
        };
    }

    //设置接收验证码按钮
    @UiThread
    void setAcceptTv() {
        afterText = getResources().getString(R.string.send_auth_code_again, time / 1000);
        accept_auth_code_tv.setText(afterText);
        changeAcceptTvStatus(false);
        time -= 1000;
        if (time < 0) {
            isTime = false;
            accept_auth_code_tv.setText(beferText);
            clearTimer();
            if (phone_et.getText().toString().length() == 11) {
                changeAcceptTvStatus(true);
            } else {
                changeAcceptTvStatus(false);
            }
        }
    }

    void changeAcceptTvStatus(boolean b) {
        if (b) {
            accept_auth_code_tv.setBackgroundResource(R.drawable.login_enable_bg);
            accept_auth_code_tv.setEnabled(true);
        } else {
            accept_auth_code_tv.setBackgroundResource(R.drawable.login_unable_bg);
            accept_auth_code_tv.setEnabled(false);
        }
    }


    void changeLoginBtnStatus(boolean b) {
        if (b) {
            login_btn.setBackgroundResource(R.drawable.login_enable_bg);
            login_btn.setEnabled(true);
        } else {
            login_btn.setBackgroundResource(R.drawable.login_unable_bg);
            login_btn.setEnabled(false);
        }
    }

    //取消定时器
    void clearTimer() {
        if (tt != null) {
            tt.cancel();
            tt = null;
        }
        if (t != null) {
            t.cancel();
            t = null;
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        clearTimer();
    }
}
